package entity

import (
	"errors"
	"time"

	"shqsoft.cn/pasnj/base"

	"github.com/jinzhu/gorm"
	log "github.com/sirupsen/logrus"
)

//ConfSttp FTP曲线
type ConfPara struct {
	ID   int      `gorm:"primary_key;column:PANO"`
	Name string   `gorm:"column:PANM;size:50"`
	PATP int      `gorm:"column:PATP"`
	PAVL *float64 `gorm:"-"`
}

//TableName FTP曲线类型表名
func (ConfPara) TableName() string {
	return "V_CONF_PARA"
}

//BasePara FTP曲线
type BasePara struct {
	ID       int        `gorm:"AUTO_INCREMENT;primary_key;column:ID"`
	PAID     int        `gorm:"column:PANO"`
	ConfPara ConfPara   `gorm:"ForeignKey:PAID"`
	PAVL     float64    `gorm:"column:PAVL"`
	BGDT     *time.Time `gorm:"column:BGDT;type:date;"`
}

//TableName FTP曲线表名
func (BasePara) TableName() string {
	return "T_BASE_PARA"
}

//判断新增是否存在
func (p *BasePara) BeforeCreate() (err error) {
	log.Debug(p)
	rows, err := base.DB.Raw("SELECT * FROM T_BASE_PARA WHERE BGDT =LEFT(?,10) AND PANO=?", p.BGDT, p.PAID).Rows()
	if err != nil {
		return err
	}
	if rows.Next() {
		return errors.New("生效日期的FTP价格曲线已存在，无法再次添加！")
	}
	return
}

//导入后执行分户处理
func BaseParaAfterImport(tx *gorm.DB, params map[string]string) (err error) {
	prams := make([]interface{}, 1)
	prams[0] = params["BGDT"]
	err = tx.Exec("exec UP_BASE_PARA ?", prams...).Error
	if err != nil {
		return err
	}
	return nil
}

//BaseParaEF 一个结构
func ConfParaEF() base.EntityFunc {
	return func() interface{} {
		entity := ConfPara{}
		return &entity
	}
}

//BaseParaESF 数组结构体
func ConfParaESF() base.EntitiesFunc {
	return func() interface{} {
		var entities []ConfPara
		return &entities
	}
}

//BaseParaEF 一个结构
func BaseParaEF() base.EntityFunc {
	return func() interface{} {
		entity := BasePara{}
		return &entity
	}
}

//BaseParaESF 数组结构体
func BaseParaESF() base.EntitiesFunc {
	return func() interface{} {
		var entities []BasePara
		return &entities
	}
}

func init() {
	relationship := []string{"ConfPara"}
	base.DaoPoolObj.Put("BasePara", base.NewDefaultDao(BaseParaEF(), BaseParaESF(), relationship))
	base.DaoPoolObj.Put("ConfPara", base.NewDefaultDao(ConfParaEF(), ConfParaESF(), nil))
	base.SetAfterCallBack("BasePara", BaseParaAfterImport)
}
